/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ro.pub.cs.dfsa.client.connection;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;

/**
 *
 * @author Narcis
 */
public class UDPClientConnection extends AbstractClientConnection {
    private DatagramSocket clientSocket;
    private InetAddress serverAddr;
    
    private static final int MAX_BYTES_PER_UDP_TRANSMISSION = 1024;
    
    public UDPClientConnection(){
        
    }
    
    @Override
    public void createConnection() throws IOException {
        DatagramSocket clientSocket = new DatagramSocket(clientPort);
        InetAddress serverAddr = InetAddress.getByName(serverAddress);
    }
    
    @Override
    public <T> T readObject(Class<T> clazz) throws IOException, ClassNotFoundException {
        byte[] recBytes = new byte[MAX_BYTES_PER_UDP_TRANSMISSION];
        DatagramPacket recPacket = new DatagramPacket(recBytes, 0, recBytes.length);
        clientSocket.receive(recPacket);
        
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(recBytes));
        T objectRead = (T) ois.readObject();
        ois.close();
        
        return objectRead;
    }

    @Override
    public void writeObject(Object o) throws IOException {
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bStream);
        
        oos.writeObject(o);
        oos.close();
        
        byte[] serializedMessage = bStream.toByteArray();
        DatagramPacket sendPacket = new DatagramPacket(serializedMessage, 0, serializedMessage.length, serverAddr, serverPort);

        clientSocket.send(sendPacket);
    }
    
    @Override
    public boolean isClosed() {
        return clientSocket == null;
    }
    
    @Override
    public void close() throws IOException {
        clientSocket = null;
    }
}
